package com.john.booter.module.user.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.john.booter.domain.entity.Role;
import com.john.booter.domain.entity.User;
import com.john.booter.domain.vo.UserVo;
import com.john.booter.exception.IdNullException;
import com.john.booter.module.role.dao.RoleDao;
import com.john.booter.module.user.dao.UserDao;
import com.john.booter.module.user.service.UserService;
import com.john.booter.pagination.DataTable;
import com.john.booter.pagination.Pager;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao dao;
	@Autowired
	private RoleDao roleDao;

	@Transactional
	@Override
	public void add(UserVo vo) {
		User user = vo.getUser();
		String roleCode = vo.getRoleCode();
		Role role = roleDao.findByCode(roleCode);
		user.setRole(role);
		dao.save(user);
	}

	@Transactional
	@Override
	public void delete(String id) {
		dao.delete(id);
	}

	@Transactional
	@Override
	public void update(UserVo vo) {
		User user = vo.getUser();
		if(StringUtils.isEmpty(user.getId())) {
			throw new IdNullException(IdNullException.defaultMsg);
		}
		String roleCode = vo.getRoleCode();
		Role role = roleDao.findByCode(roleCode);
		user.setRole(role);
		dao.update(user);
	}

	@Override
	public List<User> findAll() {
		return dao.findAll();
	}

	@Override
	public UserVo findById(String id) {
		UserVo vo = new UserVo();
		User user = dao.findById(id);
		vo.setUser(user);
		return vo;
	}

	@Override
	public User findByUsername(String username) {
		return dao.findByUsername(username);
	}

	@Override
	public DataTable<User> findDataTable(Pager pg, String username) {
		return dao.findDataTable(pg, username);
	}

	@Override
	public Role findRoleByUserId(String id) {
		// TODO Auto-generated method stub
		return null;
	}

}
